<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUpdate, VNodeRef, watch } from 'vue'
import { SystemSettings } from '@/types/modules/system-settings'

import * as api from '@/api/modules/system-settings'
import { message } from 'ant-design-vue'
import { BasicTableColumn } from '@/types'
import useTableList from '@/hooks/system/useTableList'
import useDrawer from '@/hooks/system/useDrawer'
import useCol from '@/hooks/system/useCol'

const props = defineProps({ 
  title: { type: String, default: () => 'Default Title' },
  itemData: {
    type: Object as PropType<SystemSettings>,
    default: () => ({
      sendMessage: false,
      showConsole: false,
    })
  }
})

const emit = defineEmits(['ok', 'refresh'])

const formRef = ref()
const refs = ref<any[]>([])
const formState = ref<SystemSettings>(props.itemData)

const handleBasicOk = async () => {
  let valid = await formRef.value.validate().catch((err: any) => err)
  if (!valid?.errorFields?.length) return valid
  return false
}

const handleRelateArrOk = async () => {
  let relateArr = []
  let isFailed = false
  for (let i = 0; i < refs.value.length; i++) {
    const result = await (refs.value[i] as any).handleOk()
    relateArr.push(result)
    if (!result) {
      isFailed = true
    }
  }
  if (isFailed) return false
  return relateArr
}

const handleOk = async () => {
  const basicResult = await handleBasicOk()
  const relateArrRsult = await handleRelateArrOk()

  if (basicResult && relateArrRsult) {
    return formState
  }
  return false
}

onBeforeUpdate(() => {
  refs.value = []

  formState.value = props.itemData
})

const setItemRef = (el: VNodeRef): VNodeRef => {
  if (el) {
    refs.value.push(el)
  }
  return el
}

const resetBasicForm = () => {
  formRef.value.resetFields()
}


const resetRelateArrForm = () => {
  for (let i = 0; i < refs.value.length; i++) {
    ; (refs.value[i] as any).resetForm()
  }
}

const resetForm = () => {
  resetBasicForm()
  resetRelateArrForm()
}

defineExpose({ handleOk, resetForm })

</script>

<template>
  <div>
    <a-form ref="formRef" :model="formState" :labelWrap="true">
      <h2>{{ props.title }}</h2>
      <a-form-item name="sendMessage" label="发送消息">        
        <a-switch v-model:checked="formState['sendMessage']" />
      </a-form-item>
      <a-form-item name="showConsole" label="显示控制台">
        <a-switch v-model:checked="formState['showConsole']" />
      </a-form-item>
      <a-form-item name="systemAdminCanApprove" label="系统管理员能否审批">
        <a-switch v-model:checked="formState['systemAdminCanApprove']" />
      </a-form-item>
      <a-button @click="emit('ok')">保存</a-button>
    </a-form>
  </div>
</template>

<style lang="less" scoped>
.ant-form > h2 {
  margin-bottom: 2rem;
}

.ant-form > .ant-form-item {
  margin-bottom: 12px;
}
</style>